from rest_framework import serializers
from django_redis import get_redis_connection
import logging, datetime, requests, xlrd, os, math, pymysql
from django.conf import settings
from random import randint
from geopy.distance import geodesic
from django.db.models import Count, Sum, Max, Min, Avg
from random import randint, shuffle

from equity_admin.filters_users import *
from activities.models import *
from vouchers.models import *
from orders.models import *
from equity_mall.utils.qiniu_storage import pic_upload
from equity_admin.utils import contract_add_stamp
from goods.models import *
from equity_mall.utils.utils import get_level_list, random_str
from cashbonus.models import *

logger = logging.getLogger('django')


class LevelListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account', 'account_nine', 'level')


class LevelRetrieveSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account', 'account_nine', 'level', 'address', 'longitude', 'latitude', 'telephone')


class UserInfoSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    dimensionality_choices = serializers.SerializerMethodField(read_only=True)
    map_key = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'header', 'level_id', 'level_name', 'level', 'role_name', 'dimensionality_choices',
                  'map_key')

    def get_map_key(self, obj):
        return '5PLBZ-KIZC6-NCKSH-MOPXS-QP6OK-M4BIO'

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_dimensionality_choices(self, obj):
        try:
            dic1 = {
                0: {0: '信翔'},
                1: {1: '省公司'},
                2: {2: '市公司'},
                3: {3: '区县'},
                4: {4: '网点'},
            }
            level = obj.level.level
            data = []
            for i in range(level, 5):
                data.append(dic1[i])
            return data
        except:
            return []

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class CustomerUserListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CustomerUser
        fields = ['id', 'realname', 'mobile', 'level_name', 'create_time', 'point']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class CustomerUserRetrieveModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_offline_str = serializers.CharField(source='get_is_offline_display', read_only=True)
    openid = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUser
        fields = ['id', 'username', 'realname', 'mobile', 'level', 'create_time', 'is_offline_str', 'openid', 'avatar',
                  'obtain_point', 'use_point', 'order_num', 'company_user', 'ali_user_id', 'idcode']

    def get_company_user(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_openid(self, obj):
        try:
            return obj.old_openid
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class CustomerUserPointRecordModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    business_type_str = serializers.CharField(source='get_business_type_display', read_only=True)

    class Meta:
        model = PointRecord
        fields = ['id', 'create_time', 'operate_type_str', 'business_type_str', 'point', 'point_balance', 'order_id']


class ManagerUserListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    is_developer_str = serializers.CharField(source='get_is_developer_display', read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'nickname', 'mobile', 'level_name', 'create_time', 'is_active', 'is_active_str',
                  'account', 'role_name', 'distributed_point', 'level_id', 'role_id', 'is_developer', 'is_developer_str','is_agreement',
                  'sign_time']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class ManagerUserRetrieveModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    create_user_nickname = serializers.SerializerMethodField(read_only=True)
    contract = serializers.SerializerMethodField(read_only=True)
    is_developer_str = serializers.CharField(source='get_is_developer_display', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'nickname', 'mobile', 'level', 'create_time', 'is_active', 'is_active_str',
                  'account', 'role_name', 'distributed_point', 'distributed_point_num', 'level_id', 'role_id', 'avatar',
                  'create_user_nickname', 'is_developer', 'is_developer_str', 'is_agreement', 'signature', 'sign_time',
                  'contract']

    def get_contract(self, obj):
        try:
            if obj.is_agreement == 1:
                if not obj.contract:
                    contract_pdf = f'管理承诺书_{obj.mobile}_{"%06d" % randint(0, 999999)}.pdf'
                    pdf_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/{contract_pdf}')
                    contract_add_stamp(pdf_path, obj.mobile, obj.sign_time.strftime("%Y-%m-%d"), obj.signature.url)
                    with open(pdf_path, 'rb') as f:
                        result = f.read()
                    pic_upload(result, contract_pdf)
                    obj.contract = contract_pdf
                    obj.save()
                    os.remove(pdf_path)
                    return f'https://circle.sutpay.cn/{contract_pdf}'
                else:
                    return obj.contract.url
            else:
                return ''
        except:
            return ''

    def get_create_user_nickname(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class CustomerUserViceListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUserVice
        fields = ['id', 'unionid', 'is_subscribe', 'is_wyh_customer', 'mobile', 'level_name', 'obtain_point']

    def get_level_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''


class CustomerUserViceRetrieveModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    action_area = serializers.SerializerMethodField(read_only=True)
    action_time = serializers.SerializerMethodField(read_only=True)
    bank_type = serializers.SerializerMethodField(read_only=True)
    statistics = serializers.SerializerMethodField(read_only=True)
    location = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUserVice
        fields = ['id', 'unionid', 'is_subscribe', 'is_wyh_customer', 'mobile', 'level_name', 'obtain_point', 'username',
                  'operator', 'province', 'city', 'realname', 'idcode', 'action_area', 'action_time', 'bank_type', 'avatar',
                  'statistics', 'location']

    def get_location(self, obj):
        data = {}
        try:
            customeruservicearea = obj.customeruservicearea_set.all().first()
            if customeruservicearea:
                level = customeruservicearea.level
                if level.latitude:
                    data['latitude'] = level.latitude
                    data['longitude'] = level.longitude
                else:
                    data['latitude'] = '23.141173'
                    data['longitude'] = '113.345357'
            else:
                data['latitude'] = '23.141173'
                data['longitude'] = '113.345357'
        except:
            data['latitude'] = '23.141173'
            data['longitude'] = '113.345357'
        return data

    def get_action_area(self, obj):
        data = []
        try:
            customeruservicearea_set = obj.customeruservicearea_set.all()
            for customeruservicearea in customeruservicearea_set:
                data.append(customeruservicearea.level.name)
        except:
            pass
        return data

    def get_action_time(self, obj):
        data = []
        try:
            customeruservicetime_set = obj.customeruservicetime_set.all().exclude(action_time=7)
            for customeruservicetime in customeruservicetime_set:
                data.append(customeruservicetime.get_action_time_display())
        except:
            pass
        return data

    def get_bank_type(self, obj):
        data = []
        try:
            customeruservicebanktype_set = obj.customeruservicebanktype_set.all()
            for customeruservicebanktype in customeruservicebanktype_set:
                bank_type = BankType.objects.filter(bank_code=customeruservicebanktype.bank_code).first()
                if bank_type:
                    data.append(bank_type.bank_name)
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:

            return obj.level.city_name
        except:
            return ''

    def get_statistics(self, obj):
        data = {}
        data['count'] = 0
        data['amount'] = 0
        try:
            conn = pymysql.connect(host=settings.DATABASES['business_custmoer_order_data']['HOST'],
                                   port=settings.DATABASES['business_custmoer_order_data']['PORT'],
                                   database=settings.DATABASES['business_custmoer_order_data']['NAME'],
                                   user=settings.DATABASES['business_custmoer_order_data']['USER'],
                                   password=settings.DATABASES['business_custmoer_order_data']['PASSWORD'])
            cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
            sql = f'''
            SELECT COUNT(id) AS count,SUM(money) AS amount FROM tb_o_point_order_info_{obj.id % 900} WHERE customeruservice_id={obj.id};
            '''
            cursor.execute(sql)
            row = cursor.fetchone()
            cursor.close()
            conn.close()
            if row:
                data['count'] = row['count']
                data['amount'] = row['amount']
        except:
            pass
        return data


class CustomerUserViceInviterRecordListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    inviter_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    inviter = serializers.SerializerMethodField(read_only=True)
    is_inviter_str = serializers.CharField(source='get_is_inviter_display', read_only=True)

    class Meta:
        model = CustomerUserViceInviterRecord
        fields = ['id', 'create_time', 'customeruservice', 'is_inviter', 'is_inviter_str', 'inviter_time', 'inviter_time', 'inviter']

    def get_customeruservice(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        data['openid'] = ''
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                data['realname'] = customeruservice.username
                data['mobile'] = customeruservice.mobile
                data['openid'] = customeruservice.wyh_openid
        except:
            pass
        return data

    def get_inviter(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        try:
            customeruservice = obj.inviter
            if customeruservice:
                data['realname'] = customeruservice.username
                data['mobile'] = customeruservice.mobile
        except:
            pass
        return data


class JoinCustomizeActivityListModelSerializer(serializers.ModelSerializer):

    is_join_str = serializers.CharField(source='get_is_join_display', read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    join_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = JoinCustomizeActivity
        fields = ['id', 'is_join', 'is_join_str', 'customeruservice', 'count', 'join_time']

    def get_customeruservice(self, obj):
        data = {}
        data['mobile'] = ''
        data['unionid'] = ''
        try:
            customeruservice = obj.customeruservice
            data['mobile'] = customeruservice.mobile
            data['unionid'] = customeruservice.unionid
        except:
            pass
        return data


class JoinCustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    is_join_str = serializers.CharField(source='get_is_join_display', read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    join_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # order_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = JoinCustomizeActivity
        fields = ['id', 'is_join', 'is_join_str', 'customeruservice', 'count', 'join_time']

    def get_customeruservice(self, obj):
        data = {}
        data['mobile'] = ''
        data['unionid'] = ''
        data['id'] = ''
        try:
            customeruservice = obj.customeruservice
            data['mobile'] = customeruservice.mobile
            data['unionid'] = customeruservice.unionid
            data['id'] = customeruservice.id
        except:
            pass
        return data

    def get_order_info(self, obj):
        if obj.is_join == 0:
            return []
        customizeactivity = obj.customizeactivity
        customizeactivitypayrules = customizeactivity.customizeactivitypayrules
        join_time = obj.join_time
        available_end_time = customizeactivity.available_end_time
        total_count = customizeactivitypayrules.total_count
        amount = customizeactivitypayrules.amount
        draw_counts = customizeactivitypayrules.draw_counts.split(',')
        limit_merchant_count_by_day = customizeactivitypayrules.limit_merchant_count_by_day
        if customizeactivitypayrules.is_limit_merchant == 0:
            queryset = get_point_record_db_model(obj.customeruservice_id).objects.filter(
                pay_time__gte=join_time,
                pay_time__lte=available_end_time,
                amount__gte=amount,
                customeruservice_id=obj.customeruservice_id,
                level__prov_id=7330
            ).values('shop_id').annotate(order_id=Min('id'))[0:total_count]
            if obj.is_join == 1:
                if len(queryset) >= total_count:
                    obj.is_join = 2
                obj.count = len(queryset)
                obj.save()
            order_id_list = []
            for order in queryset:
                order_id_list.append(order['order_id'])
        else:
            merchant_id_list = CustomizeActivityPayRulesLimitMerchant.objects.filter(customizeactivity_id=customizeactivity.id).values_list('merchant_id', flat=True)
            queryset = get_point_record_db_model(obj.customeruservice_id).objects.filter(
                pay_time__gte=join_time,
                pay_time__lte=available_end_time,
                amount__gte=amount,
                customeruservice_id=obj.customeruservice_id,
                merchant_id__in=merchant_id_list
            )
            order_id_list = []
            check_date_order = {}
            for order in queryset:
                if len(order_id_list) >= total_count:
                    break
                pay_time = f'{order.pay_time.strftime("%Y%m%d")}{order.merchant_id}'
                if pay_time not in check_date_order:
                    check_date_order[pay_time] = 0
                if check_date_order[pay_time] >= limit_merchant_count_by_day:
                    continue
                order_id_list.append(order.id)
                check_date_order[pay_time] = check_date_order[pay_time] + 1
            if obj.is_join == 1:
                if len(order_id_list) == total_count:
                    obj.is_join = 2
                obj.count = len(order_id_list)
                obj.save()
        queryset = get_point_record_db_model(obj.customeruservice_id).objects.filter(id__in=order_id_list)
        schedule_list = []
        for i in range(total_count):
            try:
                query = queryset[i]
                order_data = {}
                order_data['pay_time'] = query.pay_time.strftime("%Y-%m-%d %H:%M:%S")
                order_data['amount'] = query.amount
                order_data['count'] = f'第{i+1}笔'
                if query.bank_type == 'PSBC_DEBIT':
                    order_data['bank_type_sign_str'] = '邮储借记卡'
                    order_data['bank_type_sign'] = 1
                elif query.bank_type == 'PSBC_CREDIT':
                    order_data['bank_type_sign_str'] = '邮储信用卡'
                    order_data['bank_type_sign'] = 2
                else:
                    order_data['bank_type_sign_str'] = '其他'
                    order_data['bank_type_sign'] = 3
                merchant = query.merchant
                if merchant:
                    order_data['merchant_name'] = merchant.name
                    order_data['merchant_id'] = merchant.id
                else:
                    order_data['merchant_name'] = ''
                    order_data['merchant_id'] = ''
                if str(i + 1) in draw_counts:
                    if not query.customizeactivityflipcards:
                        customizeactivityrules = CustomizeActivityRules.objects.get(customizeactivity_id=customizeactivity.id, index=i + 1)
                        identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % obj.customeruservice_id}'
                        instance_data = dict()
                        instance_data['identify'] = identify
                        instance_data['customeruservice_id'] = obj.customeruservice_id
                        instance_data['mobile'] = obj.customeruservice.mobile
                        instance_data['gears'] = 1
                        instance_data['customizeactivity_id'] = customizeactivity.id
                        if customizeactivityrules.prize_type in [1, 2]:
                            instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                            instance_data['win_type'] = customizeactivityrules.prize_type
                        elif customizeactivityrules.prize_type in [3, 6]:
                            instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                            instance_data['win_type'] = customizeactivityrules.prize_type
                        instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                        if instance.win_type in [1, 2]:
                            instance.open_status = 2
                            instance.open_time = datetime.datetime.now()
                            instance.save()
                            alidiscountcoupon = instance.alidiscountcoupon
                            if alidiscountcoupon.remain_number <= 0:
                                x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                                if x:
                                    shuffle(x)
                                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                                    instance.alidiscountcoupon_id = alidiscountcoupon.id
                                    instance.save()
                                else:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                            activity_id = alidiscountcoupon.id
                            while True:
                                alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                                activity_origin_send_count = alidiscountcoupon.send_count
                                activity_origin_remain_number = alidiscountcoupon.remain_number
                                activity_new_send_count = activity_origin_send_count + 1
                                activity_new_remain_number = activity_origin_remain_number - 1
                                if activity_new_remain_number < 0:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                result = AliDiscountCoupon.objects.filter(id=activity_id,send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                                if result == 0:
                                    continue
                                break
                            alidiscountcouponinfo_data = {}
                            alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                            alidiscountcouponinfo_data['level_id'] = instance.level_id
                            alidiscountcouponinfo_data['status'] = 0
                            alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                            out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % obj.customeruservice_id}'
                            alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                            alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                            alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                            instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                            instance.save()
                        else:
                            instance.open_status = 2
                            instance.open_time = datetime.datetime.now()
                            instance.save()
                            cashactivity = instance.cashactivity
                            cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                            if cashactivityrule.amount > cashactivity.remain_amount:
                                instance.open_status = 3
                                instance.win_type = 4
                                instance.open_time = datetime.datetime.now()
                                instance.save()
                            amount = cashactivityrule.amount
                            activity_id = cashactivity.id
                            while True:
                                activity = CashActivity.objects.get(id=activity_id)
                                activity_origin_take_amount = activity.take_amount
                                activity_origin_remain_amount = activity.remain_amount
                                if activity_origin_remain_amount < amount:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                activity_new_take_amount = activity_origin_take_amount + amount
                                activity_new_remain_amount = activity_origin_remain_amount - amount
                                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                                if result == 0:
                                    continue
                                break
                            date_now = datetime.datetime.now()
                            activity_data = {}
                            activity_data['amount'] = amount
                            activity_data['create_time'] = date_now
                            activity_data['cash_activity_id'] = activity.id
                            activity_data['level_id'] = instance.level_id
                            activity_data['state'] = 1
                            identify = random_str()
                            nonce_str = random_str()
                            activity_data['identify'] = identify
                            activity_data['nonce_str'] = nonce_str
                            activity_data['desc'] = activity.name
                            activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%07d" % obj.customeruservice_id}'
                            activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                            activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                            instance.cashactivitydata_id = activity_dat.id
                            instance.amount = amount
                            instance.save()
                        query.customizeactivityflipcards_id = instance.id
                        query.save()
                    else:
                        instance = query.customizeactivityflipcards
                    order_data['open_status'] = instance.open_status
                    order_data['open_status_str'] = instance.get_open_status_display()
                    order_data['activity_name'] = instance.alidiscountcoupon.activity_name
                else:
                    order_data['open_status'] = ''
                    order_data['open_status_str'] = ''
                    order_data['activity_name'] = ''
                schedule_list.insert(0, order_data)
            except:
                pass
        return schedule_list


class BindCardOrderListModelSerializer(serializers.ModelSerializer):

    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    prize_status_str = serializers.CharField(source='get_prize_status_display', read_only=True)
    bank_type_sign_str = serializers.CharField(source='get_bank_type_sign_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customizeactivityflipcards = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    bank_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = BindCardOrder
        fields = ['id', 'order_status', 'order_status_str', 'prize_status', 'prize_status_str', 'create_time', 'user_received_account',
                  'customizeactivityflipcards', 'customeruservice', 'bank_type', 'bank_type_sign', 'bank_type_sign_str']

    def get_customeruservice(self, obj):
        data = {}
        data['mobile'] = ''
        data['unionid'] = ''
        try:
            customeruservice = obj.customeruservice
            data['mobile'] = customeruservice.mobile
            data['unionid'] = customeruservice.unionid
        except:
            pass
        return data

    def get_customizeactivityflipcards(self, obj):
        data = {}
        data['received_time'] = ''
        data['activity_name'] = ''
        try:
            customizeactivityflipcards = obj.customizeactivityflipcards
            if customizeactivityflipcards:
                data['received_time'] = customizeactivityflipcards.received_time.strftime("%Y-%m-%d %H:%M:%S")
                if customizeactivityflipcards.win_type in [1, 2]:
                    data['activity_name'] = customizeactivityflipcards.alidiscountcoupon.activity_name
                elif customizeactivityflipcards.win_type in [3]:
                    data['activity_name'] = customizeactivityflipcards.cashactivity.name
        except:
            pass
        return data

    def get_bank_type(self, obj):
        try:
            bank_type = obj.bank_type
            bank = BankType.objects.filter(bank_code=bank_type).first()
            if bank:
                return bank.bank_name
            else:
                return ''
        except:
            return ''


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level_name']

    def get_business_form(self, obj):
        data = {}
        try:
            if obj.customizeactivity.is_business_form == 1:
                business_form = obj.customizeactivitybusinessform
                data['business_name'] = business_form.business_name
                data['business_account'] = business_form.business_account
                data['business_amount'] = business_form.business_amount
                data['business_type'] = business_form.business_type
                data['business_type_str'] = business_form.get_business_type_display()
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_customercser_mobile(self, obj):
        try:
            return obj.mobile
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['amount'] = alidiscountcoupon.amount
            elif prize_type == 5:
                data['id'] = ''
                data['activity_name'] = f'{obj.point} 积分'
                data['activity_id'] = ''
                data['rule'] = f'{obj.point} 积分'
                data['amount'] = f''
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['amount'] = obj.cashactivitydata.amount
        except:
            pass
        return data


class BindCardOrderRetrieveModelSerializer(serializers.ModelSerializer):

    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    prize_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    success_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    bank_type = serializers.SerializerMethodField(read_only=True)
    customizeactivityflipcards = CustomizeActivityFlipCARDSListModelSerializer()
    bank_type_sign_str = serializers.CharField(source='get_bank_type_sign_display', read_only=True)

    class Meta:
        model = BindCardOrder
        fields = ['id', 'amount', 'order_status', 'order_status_str', 'prize_status', 'prize_status_str', 'create_time', 'user_received_account',
                  'out_trade_no', 'refund_id', 'transaction_id', 'message', 'bank_type', 'success_time', 'refund_time', 'customizeactivityflipcards',
                  'bank_type_sign', 'bank_type_sign_str']

    def get_bank_type(self, obj):
        try:
            bank_type = obj.bank_type
            bank = BankType.objects.filter(bank_code=bank_type).first()
            if bank:
                return bank.bank_name
            else:
                return ''
        except:
            return ''

